package cn.itsource.basic.other.interceptor;

import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.PetHomeConstant;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.domain.LoginInfo;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component //交给spring管理
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisService redisService;

    /**
     * 在执行目标方法（Controller里面的方法）之前执行
     * true:放行 false:拦截，不让你执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("访问的地址："+request.getRequestURI());

        //1.获取请求头中的token字符串
        String token = request.getHeader("token");
        // 1,1如果token为空，返回json里面要带登录超时的code：SYSTEM_LOGIN_TIME_OUT
        if (StringUtils.isBlank(token)) {
            //响应一个json字符串回去
            return timeout(response);
        }

        //2.根据token去redis中获取登录信息
        LoginInfo loginInfo = redisService.getKeyObjectValue(token, LoginInfo.class);
        //3.如果获取不到，返回false  返回json里面要带登录超时的code：SYSTEM_LOGIN_TIME_OUT
        if (loginInfo == null){
            //响应一个json字符串回去
            return timeout(response);
        }
        //4.获取到了，重新存进去，刷新30分钟
        redisService.setStringKeyAndValue(token,loginInfo,30);

        return true;
    }

    private boolean timeout(HttpServletResponse response) throws IOException {
        AjaxResult result = AjaxResult.createError(PetHomeConstant.SYSTEM_LOGIN_TIME_OUT, "没有登录，get out");
        //转成json字符串
        String jsonString = JSONObject.toJSONString(result);
        //设置返回类型，浏览器才会知道怎么解析
        response.setContentType("application/json;charset=UTF-8");
        //通过resp响应回去
        PrintWriter writer = response.getWriter();
        writer.write(jsonString);
        return false;
    }


    public static void main(String[] args) {
        AjaxResult result = AjaxResult.createError(PetHomeConstant.SYSTEM_LOGIN_TIME_OUT, "没有登录，get out");

        System.out.println(result);
        System.out.println(JSONObject.toJSONString(result));


    }

}
